<template>
	<!-- 基本信息 -->
	<div >
		<FormPanel
			ref="FormPanel"
			:list="initForm"
			:cols="2"
			:formType="formType"
			:labelWidth="150"
			:isSubmitBtn="false"
			@formChange="formChangeHandle"
			class="mtop"
		/>
        <BaseDialog
            title="选择车型"
            :visible.sync="visibleDialog"
            width="700px"
            destroyOnClose
            :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
		>
            <infoModal selectType="multiple" @close="selectModelBack"/>
        </BaseDialog>
		<BaseDialog
            title="选择客户公司"
            :visible.sync="clueVisible"
            width="80vw"
            destroyOnClose
            :containerStyle="{height: 'calc(100% - 100px)', overflow: 'auto', paddingBottom: '60px'}"
		>
			<dealerList selectType="single" :isSelectColumnList="isSelectColumnList" @close="closeClueDialog" @save="selctClubDialog"/>
		</BaseDialog>
	</div>
</template>

<script>
	import infoModal from '@/pages/cms-common/model';//车型
	import dealerList from '@/pages/cms-common/clue/dealerList'
	import { getClubById } from '@/api/cms-api/customerManage/clue/createClue';//线索（显示更多信息）

	import { region } from '@/api/cms-common/region';//行政区域
	import { dictionary } from '@/utils/dictMixin';

	export default {
		mixins: [dictionary,region],
		components:{infoModal,dealerList},
		model:{
			prop:'pdata',
			event:'click'
		},
		props: {
			pdata: {
				type: Object,
				default: () => ({})
			},
			formType:{
				type: String,
				required:true
			}
		},
		data() {
			return {
				isLicenseAll:10041001,
				initForm: this.initFormFun(),
				visibleDialog: false,
				clueVisible: false,
				isSelectColumnList:[]
			};
		},
		methods: {
			//初始化数据（由外部调用）
			init() {
				//先处理数据（回显或选择线索后）
				let isLicenseAll = this.pdata.allForm.isLicenseAll;//是否全国上牌
				if(isLicenseAll === this.isLicenseAll){//如果是全国上牌
					this.initForm.find(item => item.fieldName === 'licenseProvincesList').type = 'MULTIPLE_SELECT';
					//上牌城市不可编辑
					let licenseCityConfig = this.initForm.find(item => item.fieldName === 'licenseCity');
					if(this.formType != 'show'){
						licenseCityConfig.disabled = true;
					}
					licenseCityConfig.initialValue = '';
					licenseCityConfig.rules = [];
					let licenseProvinces = this.pdata.allForm.licenseProvinces;//上牌省份
					if(licenseProvinces){
						let list = licenseProvinces.split(',');
						let intList = list.map(x => parseInt(x));
						this.pdata.allForm.licenseProvincesList = intList;
					}
				}else{
					this.initForm.find(item => item.fieldName === 'licenseProvincesList').type = 'SELECT';
					//上牌城市不可编辑
					let licenseCityConfig = this.initForm.find(item => item.fieldName === 'licenseCity');
					if(this.formType != 'show'){
						licenseCityConfig.disabled = false;
					}
					licenseCityConfig.rules = licenseCityConfig.rulesTmp;
					// licenseCityConfig.initialValue = '';
					//如果不是则为单选（上牌城市）
					let licenseProvinces = this.pdata.allForm.licenseProvinces;//上牌省份
					if(licenseProvinces){
						this.pdata.allForm.licenseProvincesList = parseInt(licenseProvinces);
					}
				}
				//赋值
				this.initForm.forEach(x => {
					//为空则不填进去，就不触发验证了
					if(this.pdata.allForm[x.fieldName]){
						x.initialValue = this.pdata.allForm[x.fieldName];
					}
				});
				this.isSelectColumnList = this.pdata.allForm.clueId;
				//初始化省份
				this.initProvince();
				this.initRegion(this.pdata.allForm.customerProvince,this.pdata.allForm.customerCity);
				this.initCity2(this.pdata.allForm.licenseProvincesList,false);
			},
			formChangeHandle(val) {
				this.pdata.allForm = Object.assign(this.pdata.allForm,val);
				if(!this.pdata.allForm.clueId){
					this.$notify.warning({title: '提示信息',message:'请选择客户公司！'});
					return;
				}
				if(!this.pdata.allForm.majorManagerId){
					this.$notify.error({title: '提示信息',message:'您还没有所属的大客户事业部，不可以保存！'});
					return;
				}
				//如果是全国上牌，则拼接一下，如果不是则不拼接
				if(this.pdata.allForm.isLicenseAll === this.isLicenseAll){
					if(Array.isArray(this.pdata.allForm.licenseProvincesList)){
						this.pdata.allForm.licenseProvinces = this.pdata.allForm.licenseProvincesList.join(",");
					}
				}else{
					this.pdata.allForm.licenseProvinces = this.pdata.allForm.licenseProvincesList;
				}
				if(String(this.pdata.allForm.estimatePurchaseDate).indexOf("-01 00:00:00") == -1){
					this.pdata.allForm.estimatePurchaseDate = this.pdata.allForm.estimatePurchaseDate + "-01 00:00:00";
				}
				//传递数据到父组件里
				this.$emit('click', this.pdata);
				//触发外部的事件，以标志着本表单已经准备完毕
				this.$emit('formchange', this.pdata);
			},
			saveDialog(){
				this.$refs.FormPanel.SUBMIT_FORM();
			},
			//回显市和区县
			initRegion(provinceId,cityId){
				this.initCity(provinceId,false);
				this.initTown(cityId,false);
			},
			//初始化所在省份，上牌省份
			async initProvince(){
				let pl = await this.createRegionList();
				this.initForm.find(item => item.fieldName === 'customerProvince').itemList = pl;
				this.initForm.find(item => item.fieldName === 'licenseProvincesList').itemList = pl;
			},
			//初始化所在市数据
			async initCity(provinceId,flag = true){
				if(!provinceId || provinceId==null || typeof(provinceId)=='undefined'){
					return;
				}
				//市
				let city = this.initForm.find(item => item.fieldName === 'customerCity');
				//清空下级数据[市，区县]（在修改时，回显时的时候不清空，在新增时，变更值时清空）
				if(flag){
					city.initialValue = '';
					//区县
					let district = this.initForm.find(item => item.fieldName === 'customerDistrict');
					district.initialValue = '';
					district.itemList = [];
				}
				//取省数据
				let rd = this.getRegionData();
				this.cityData = rd[provinceId].children;
				let cl = this.createSubRegionList(this.cityData);
				city.itemList = cl;
			},
			//初始化所在县市数据
			async initTown(cityId,flag = true){
				if(!cityId || cityId==null || typeof(cityId)=='undefined'){
					return;
				}
				let district = this.initForm.find(item => item.fieldName === 'customerDistrict');
				//清空下级数据[区县]（在修改时，回显时的时候不清空，在新增时，变更值时清空）
				if(flag){
					district.initialValue = '';
				}
				let td = this.cityData[cityId].children;
				let tl = this.createSubRegionList(td);
				district.itemList = tl;
			},
			//初始化所在市数据(上牌城市)
			async initCity2(provinceId,flag = true){
				if(Array.isArray(provinceId)){
					return;
				}
				if(!provinceId || provinceId==null || typeof(provinceId)=='undefined'){
					return;
				}
				let licenseCity = this.initForm.find(item => item.fieldName === 'licenseCity');
				//清空下级数据
				if(flag){
					licenseCity.initialValue = '';
				}
				//取省数据
				let rd = this.getRegionData();
				this.cityData = rd[provinceId].children;
				let cl = this.createSubRegionList(this.cityData);
				licenseCity.itemList = cl;
			},
			//车型弹窗打开
            openModelDialog() {
                this.visibleDialog = true;
            },
    		//车型选择回显
			selectModelBack(data) {
				if(!data.data){
					this.visibleDialog = false; //关闭弹窗
					return ;
				}
				let modelNames = new Array();
				let modelIds = new Array();
				if(data && data.data && typeof(data.data)!=null && data.data.length>0){
					(data.data || []).forEach(models => {
						modelNames.push(models.modelName);//回显选择车型名称
						modelIds.push(models.modelId);//存储车型ID
					});
				}
				this.initForm.find(item => item.fieldName === 'intentionModelName').initialValue = modelNames.join(",");
				this.pdata.allForm.intentionModel = modelIds.join(",");
				this.visibleDialog = false; //关闭弹窗
			},
			//打开大客户弹窗
			openClueDialog(){
				this.clueVisible = true;
			},
			//大客户弹窗关闭后
			closeClueDialog(){
				this.clueVisible = false;
			},
			//大客户弹窗选中后
			async selctClubDialog(data){
				//删除之前自动填写的联系人
				this.pdata.majorProjectContact.list.splice(this.pdata.majorProjectContact.list.findIndex(x => x.contactName == this.pdata.allForm.keyLinkMan),1);
				this.isSelectColumnList = data.clueId;
				//get一遍再融合，能显示出需要显示的字段
				let res = await getClubById(data.clueId);
				if(res.resultCode === 200){
					if(res.data.depListIsExistence === 'existence'){
						if(Array.isArray(res.data.depFindList)){
							//取出大客户区域的ID，没有的话则这不能添加
							res.data.majorManagerId = res.data.depFindList[0].MAJOR_MANAGER_ID;
						}
					}else{
						//报出错误
					}
					//isLicenseAll;//是否全国上牌
					this.pdata.allForm = Object.assign(this.pdata.allForm,res.data);
					this.pdata.allForm.licenseProvincess = data.licenseProvinces;
					this.pdata.allForm.projectName = res.data.customerName;
					this.pdata.allForm.realTimeDealerName = res.data.dealerName;
					//重新回显
					this.$nextTick(() => {
						this.init();
						this.$parent.$refs.projectForm.init();
					});
					//设置默认为编辑
					let contactData = {
						"contactType":"","contactName":"","contactSex":"","contactJob":"","contactMobile":"","contactEmail":"","birthday":"","homeAddress":"","hobby":"",
						"contactTypeIsEdit":true,"contactNameIsEdit":true,"contactSexIsEdit":true,"contactJobIsEdit":true,"contactMobileIsEdit":true,"contactEmailIsEdit":true,"birthdayIsEdit":true,"homeAddressIsEdit":true,"hobbyIsEdit":true
					};
					contactData.contactName = data.keyLinkMan;
					contactData.contactMobile = data.linkPhone;
					this.pdata.majorProjectContact.list.push(contactData);
					this.clueVisible = false;
				}
			},
			//清空数据
			clearClue(){
				this.isSelectColumnList = "";
				//事业部，经销商留存
				//let orgNameObj = this.initForm.find(x => x.fieldName === 'majorManagerId');
				let dealerNameObj = this.initForm.find(x => x.fieldName === 'realTimeDealerName');
				//let orgName = orgNameObj.initialValue;
				let dealerName = dealerNameObj.initialValue;

				//清空表单内容（不包含隐藏值）
				this.$refs.FormPanel.RESET_FORM();
				this.pdata.allForm.intentionModel = "";
				this.pdata.allForm.majorManagerId = "";
				//取的表单值（不包含隐藏值）
				this.$refs.FormPanel.excuteFormData(this.$refs.FormPanel.form);
				this.pdata.allForm = Object.assign(this.pdata.allForm,this.$refs.FormPanel.form);
				//this.pdata.allForm.orgName = orgName;
				this.pdata.allForm.realTimeDealerName = dealerName;
				//重新回显
				this.$nextTick(() => {
					this.init();
				});

				//删除之前自动填写的联系人
				// let majorProjectContactIndex = -1;
				// this.pdata.majorProjectContact.list.find((x,i) => {
				// 	if(x.contactName == this.pdata.allForm.keyLinkMan){
				// 		majorProjectContactIndex = i;
				// 		return true;
				// 	}
				// 	return false;
				// });

				// if(majorProjectContactIndex != -1){
				// 	this.pdata.majorProjectContact.list.splice(majorProjectContactIndex,1);
				// }
				//删除之前自动填写的联系人
				this.pdata.majorProjectContact.list.splice(this.pdata.majorProjectContact.list.findIndex(x => x.contactName == this.pdata.allForm.keyLinkMan),1);
			},
			//是否全国上牌选项变更，是：上牌省份可多选，上牌城市不可编辑；否：上牌省份和城市单选
			isLicenseAllChange(value){
				this.initForm.find(item => item.fieldName === 'licenseCity').itemList = [];
				this.initForm.find(item => item.fieldName === 'licenseCity').initialValue = '';
				if(value == this.isLicenseAll){//全国上牌
					//上牌城省多选
					let licenseProvincesList = this.initForm.find(item => item.fieldName === 'licenseProvincesList');
					licenseProvincesList.initialValue = [];
					this.$nextTick(() => {
						licenseProvincesList.type = 'MULTIPLE_SELECT';
					});
					//上牌城市不可编辑
					this.initForm.find(item => item.fieldName === 'licenseCity').disabled = true;
				}else{
					//上牌城省单选
					let licenseProvincesList = this.initForm.find(item => item.fieldName === 'licenseProvincesList');
					licenseProvincesList.initialValue = '';
					this.$nextTick(() => {
						licenseProvincesList.type = 'SELECT';
					});
					//上牌城市不可编辑
					this.initForm.find(item => item.fieldName === 'licenseCity').disabled = false;
				}
			},
			//表单数据
			initFormFun() {
				return [
					{
						type: 'INPUT',
						label: '客户公司名称',
						fieldName: 'customerName',
						readonly:true,
						initialValue: '',
						maxlength:200,
						rules:[
							{required: true, message: '必填', trigger: 'blur' },
							{ min: 0, max: 200, message: '长度在 0 到 200 个字符', trigger: 'blur' }
						],
						placeholder:'',
						unitRender: () => {
							// <el-divider direction="vertical" />
							return (<div>
								<el-button slot="append" icon="el-icon-search" onClick={() => this.openClueDialog()}></el-button>
								<el-button slot="append" icon="el-icon-delete" onClick={() => this.clearClue()}></el-button>
							</div>);
						}
					},
					{
						type: 'SELECT',
						label: '客户类型',
						fieldName: 'customerType',
						initialValue: '',
						itemList: this.createDictList('2506'),
						placeholder:'',
						rules:[
							{required: true, message: '必填', trigger: 'change' },
						],
					},
					{
						type: 'SELECT',
						label: '客户性质',
						fieldName: 'customerProperty',
						initialValue: '',
						itemList: this.createDictList('2534'),
						placeholder:'',
					},
					{
						type: 'SELECT',
						label: '客户状态',
						fieldName: 'customerStatus',
						initialValue: '',
						itemList: this.createDictList('2507'),
						placeholder:'',
					},
					{
						type: 'SELECT',
						label: '客户来源',
						fieldName: 'customerSource',
						initialValue: '',
						itemList: this.createDictList('2508'),
						placeholder:'',
					},
					{
						type: 'DATE',
						label: '建档时间',
						disabled:true,
						fieldName: 'recordDate',
						valueFormat: 'yyyy-MM-dd ',
						style: { width: '100%' },
						initialValue: '',
						placeholder:'',
					},
					{
						type: 'SELECT',
						label: '省份',
						fieldName: 'customerProvince',
						initialValue: '',
						itemList: [],
						change: props => this.initCity(props),
						placeholder:'',
						rules: [{required: true,message: '必填',trigger: 'change'}]
					},
					{
						type: 'SELECT',
						label: '市',
						fieldName: 'customerCity',
						initialValue: '',
						itemList: [],
						change: props => this.initTown(props),
						placeholder:'',
					},
					{
						type: 'SELECT',
						label: '县区',
						fieldName: 'customerDistrict',
						initialValue: '',
						itemList: [],
						placeholder:'',
					},
					{
						type: 'INPUT',
						label: '社会统一信用代码',
						fieldName: 'uniformSocialCreditCode',
						maxlength:32,
						initialValue: '',
						placeholder:'',
						rules: [{required: true,message: '必填',trigger: 'change'}]
					},
					{
						type: 'TEXT_AREA',
						label: '详细地址',
						fieldName: 'customerAddress',
						selfCols:2,
						rows: 1,
						maxlength:200,
						initialValue: '',
						placeholder:'',
					},
					{
						type: 'SELECT',
						label: '客户等级',
						fieldName: 'customerLevel',
						initialValue: '',
						itemList: this.createDictList('2509'),
						placeholder:'',
					},
					{
						type: 'SELECT',
						label: '所属行业分类',
						fieldName: 'industryCategory',
						initialValue: '',
						itemList: this.createDictList('2510'),
						placeholder:'',
					},
					{
						type: 'SELECT',
						label: '行业地位',
						fieldName: 'industryStatus',
						initialValue: '',
						itemList: this.createDictList('2511'),
						placeholder:'',
					},
					{
						type: 'SELECT',
						label: '采购方式',
						fieldName: 'purchaseMode',
						initialValue: '',
						itemList: this.createDictList('2512'),
						placeholder:'',
					},
					{
						type: 'INPUT',
						label: '意向车型',
						fieldName: 'intentionModelName',
						initialValue: '',
						// itemList: this.createDictList('1008')
						readonly : true,
						unitRender: () => {
							return <el-button slot="append" icon="el-icon-search" onClick={() =>this.openModelDialog()}></el-button>
						},
						placeholder:'',
					},
					{
						type: 'INPUT_NUMBER',
						label: '预计采购数量',
						fieldName: 'estimatePurchaseNum',
						initialValue: undefined,
						precision: 0,
						max:99999999,
						min:0,
						rules:[
							{ required: true, message: "必填", trigger: "blur"},
							{ required: true, message: "必填", trigger: "change"}
						],
						placeholder:'',
					},
					{
						type: 'SELECT',
						label: '购车用途',
						fieldName: 'buyPurpose',
						initialValue: '',
						itemList: this.createDictList('2513'),
						placeholder:'',
					},
					{
						type: 'DATE',
						label: '预计采购日期',
						fieldName: 'estimatePurchaseDate',
						valueFormat: 'yyyy-MM',
						dateType:'month',
						style: { width: '100%' },
						initialValue: '',
						placeholder:'',
					},
					{
						type: 'SELECT',
						label: '预算来源',
						fieldName: 'budgetSource',
						initialValue: '',
						itemList: this.createDictList('2514'),
						placeholder:'',
					},
					{
						type: 'INPUT_NUMBER',
						label: '年度预算',
						fieldName: 'yearBudget',
						initialValue: undefined,
						precision: 2,
						max:9999999999999999.99,
						min:0,
						rules:[
							{ required: true, message: "必填", trigger: ['blur','change']},
						],
						placeholder:'',
					},
					{
						type: 'SELECT',
						label: '是否全国上牌',
						fieldName: 'isLicenseAll',
						initialValue: '',
						itemList: this.createDictList('1004'),
						rules:[
							{ required: true, message: "必填", trigger: ['blur','change']},
						],
						change : this.isLicenseAllChange,
						placeholder:'',
					},
					{
						type: 'SELECT',
						label: '上牌省份',
						fieldName: 'licenseProvincesList',
						initialValue: '',
						itemList: [],
						change: props => this.initCity2(props),
						placeholder:'',
						rules:[
							{required: true, message: '必填', trigger:['blur','change'] },
						],
					},
					{
						type: 'SELECT',
						label: '上牌城市',
						fieldName: 'licenseCity',
						initialValue: '',
						itemList: [],
						placeholder:'',
						// rules:[
						// 	{required: true, message: '必填', trigger: ['blur','change'] },
						// ],
						rulesTmp:[{required: true, message: '必填', trigger: ['blur','change'] },],
					},
					{
						type: 'SELECT',
						label: '是否跨区销售',
						fieldName: 'isCrossSbu',
						initialValue: '',
						itemList: this.createDictList('1004'),
						placeholder:'',
						rules:[
							{required: true, message: '必填', trigger: ['blur','change'] },
						],
					},
					{
						type: 'INPUT',
						label: '融资渠道',
						fieldName: 'financeChannel',
						maxlength:100,
						initialValue: '',
						rules:[
							{ min: 0, max: 100, message: '长度在 0 到 100 个字符', trigger: 'blur' }
						],
						placeholder:'',
					},
					// {
					// 	type: 'INPUT',
					// 	label: '客户关键联系人',
					// 	fieldName: 'keyLinkMan',
					// 	maxlength:100,
					// 	initialValue: '',
					// 	rules:[
					// 		{ min: 0, max: 100, message: '长度在 0 到 100 个字符', trigger: 'blur' }
					// 	],
					// },
					// {
					// 	type: 'INPUT',
					// 	label: '联系方式',
					// 	fieldName: 'linkPhone',
					// 	initialValue: '',
					// 	maxlength:50,
					// 	rules:[
					// 		{ min: 0, max: 50, message: '长度在 0 到 50 个字符', trigger: 'blur' }
					// 	],
					// },
					// {type: 'INPUT',label:'事业部',fieldName:'orgName',disabled: true,placeholder:'',},
					{type: 'SELECT',label:'事业部',fieldName:'majorManagerId',disabled: true,placeholder:'',
						itemList: this.createDictList('2566'),
					},
					{type: 'INPUT',label:'经销商',fieldName:'realTimeDealerName',disabled: true,placeholder:'',},
					{
						type: 'TEXT_AREA',
						label: '备注',
						fieldName: 'remark',
						initialValue: '',
						selfCols:2,
						rows: 2,
						maxlength:200,
						rules:[
							{ min: 0, max: 200, message: '长度在 0 到 200 个字符', trigger: 'blur' }
						],
						placeholder:'',
					}
				];
			}
		}
	};
</script>